<template>
  <Dialog :title="title" :loading="loading" :visible="visible" button-text="保存" @close="handleClose" @confirm="handleConfirm">
    <el-form ref="ruleForm" :loading="loading" :model="ruleForm" label-width="auto" style="width:40%">
      <!-- 筛选顾客已购买的项目,检查项除外 -->
      <el-form-item label="顾客：" prop="customerName">
        <el-autocomplete
          v-model="ruleForm.customerName"
          :fetch-suggestions="querySearch"
          placeholder="请输入内容"
          clearable
          @select="handleSelect"
          @clear="customerClear"
        />
      </el-form-item>
      <el-form-item v-show="customerProjectShow" label="所属项目：" prop="projectName">
        <el-select
          v-model="ruleForm.projectId"
          filterable
          placeholder="请选择项目"
          class="el-select-y"
          @change="projectChange"
        >
          <!-- :disabled="!choice" -->
          <el-option
            v-for="item in projectNameOptions"
            :key="item.id"
            :label="item.projectName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-show="warehouseList.length > 1" label="仓库：" prop="warehouseId">
        <el-select v-model="ruleForm.warehouseId" class="el-select-y" filterable placeholder="请选择" @change="handleSelectWarehouse">
          <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <div style="padding-top:20px;clear:both;">挑选</div>
    <el-container class="choose">
      <el-aside width="195x">
        <LeftClassification :tabs-text="tabsText" @classificationClist="getClassificationId" @tabsVales="handleTabs" />
      </el-aside>
      <el-main>
        <div>
          <el-input v-model="val" placeholder="请输入名称和拼音码" style="width:30%" @input="valChange" />
          <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" border :row-class-name="tableColor" style="width: 100%" @select="handlechange" @select-all="allHandleChange">
            <el-table-column label="名称" prop="name" :show-overflow-tooltip="true" />
            <el-table-column prop="searchCode" label="拼音码" :show-overflow-tooltip="true" />
            <el-table-column prop="spec" label="规格" :show-overflow-tooltip="true" />
            <el-table-column prop="unit" label="单位" :show-overflow-tooltip="true" />
            <el-table-column prop="sellPrice" label="售价" :show-overflow-tooltip="true" />
            <el-table-column
              type="selection"
              label="操作"
              :show-overflow-tooltip="true"
              width="55"
            />
          </el-table>
        </div>
      </el-main>
    </el-container>
    <div style="padding-top:20px;clear:both;">领取清单</div>
    <el-table :data="selectTables" border :row-class-name="tableColor" tooltip-effect="dark" style="width: 100%">
      <el-table-column label="名称" prop="name" :show-overflow-tooltip="true" />
      <el-table-column label="类型" prop="name" :show-overflow-tooltip="true" />
      <el-table-column prop="spec" label="规格" :show-overflow-tooltip="true" />
      <el-table-column prop="unit" label="单位" :show-overflow-tooltip="true" />
      <el-table-column prop="useFunction" label="用法" min-width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dictionary-selector class="el-select-y" :disabled="scope.row.type == '物品'" code="swan_department_ypyf" :value.sync="scope.row.useFunction" />
        </template>
      </el-table-column>
      <el-table-column prop="useNumber" label="频率" min-width="120" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <dictionary-selector class="el-select-y" :disabled="scope.row.type == '物品'" code="swan_department_ypsypl" :value.sync="scope.row.useNumber" />
        </template>
      </el-table-column>
      <el-table-column prop="sellPrice" label="售价" :show-overflow-tooltip="true" />
      <el-table-column prop="availableStock" label="可用库存" :show-overflow-tooltip="true" />
      <el-table-column prop="dataCount" label="领取数量" :show-overflow-tooltip="true">
        <template slot-scope="{ row }">
          <el-input v-model="row.dataCount" :min="1" oninput="if(isNaN(value)) { value = null } if(value.indexOf('.')>0){value=value.slice(0,value.indexOf('.')+3)}" :max="10" label="描述文字" />
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="{ row }">
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </Dialog>
</template>

<script>
import Dialog from "@/components/Dialog";
import LeftClassification from "@/components/leftClassification";
import { tableColor } from '@/utils/common.js';
export default {
  components: { Dialog, LeftClassification },
  props: {

  },
  data() {
    return {
      tableColor,
      ruleForm: {},
      value: '',
      val: "",
      loading: false,
      tabsText: [
        { label: '物品', name: 'goods' },
        { label: '药品', name: 'drugs' },
      ],
      searchParams: {
        page: 1,
        pageSize: 999999,
      },
      customerProjectShow: true,
      tableData: [],
      tableDataList: [],
      selectTables: [],
      department: '',
      projectNameOptions: [],
      warehouseList: [],
      visible: false,
      selectRow: {},
      title: '新增领取',
      tabsBool: 1,
      tabCurrType: "物品类",
      restaurants: [],
      wareHouseOldValId: "",
      wareHouseOldValName: "",
    };
  },
  mounted() {
    const nameList = [];
    const deptUsrList = this.$store.getters.currentUserInfo.deptUsrList;
    deptUsrList.forEach(item => {
      nameList.push(item.deptName);
    });
    this.department = nameList.join(">");
  },
  methods: {

    openDialog(row) {
      this.selectRow = row;
      this.visible = true;
      this.selectTables = [];
      this.tableData = [];
      this.ruleForm = row;
      this.loadAll();
      this.warehouseListHandle();
      this.$set(this.ruleForm, "deptType", "科室领取");
      if (this.ruleForm.id) {
        this.title = "编辑领取";
        this.loadSelectData(row);
      }
    },
    async loadSelectData(row) {
      const res = await this.$api['department/useDrugGoods/details']({ id: row.id });
      if (res.code !== 200) return this.$message.error(res.msg);
      res.data.listDto.forEach(item => {
        item.id = item.drugId;
        this.selectTables.push(item);
      });
    },
    handleTabs(val) {
      if (val === 'goods') {
        this.tabsBool = 1;
      } else {
        this.tabsBool = 2;
      }
      this.val = "";
      this.tableData = [];
    },
    handleSelectWarehouse(id) {
      if (this.selectTables.length > 0) {
        this.$confirm('切换仓库后选择的数据将被清空，是否切换?')
          .then(_ => {
            this.selectTables = [];
            this.tableData = [];
            this.ruleForm.warehouseId = id;
            this.warehouseList.map(item => {
              if (item.id === id) {
                this.ruleForm.warehouseName = item.name;
              }
            });
            this.wareHouseOldValId = id;
            this.wareHouseOldValName = this.ruleForm.warehouseName;
          })
          .catch(_ => {
            this.$set(this.ruleForm, 'warehouseId', this.wareHouseOldValId);
            this.$set(this.ruleForm, 'warehouseName', this.wareHouseOldValName);
          });
      } else {
        this.ruleForm.warehouseId = id;
        this.warehouseList.map(item => {
          if (item.id === id) {
            this.ruleForm.warehouseName = item.name;
          }
        });
      }
    },
    // 仓库
    warehouseListHandle() {
      this.warehouseList = [];
      const list = JSON.parse(localStorage.WARE_HOUSE);
      list.forEach(item => {
        if (item.grant.indexOf("领用仓库") > -1) {
          this.warehouseList.push(item);
        }
      });
      if (this.warehouseList.length > 0) {
        this.$set(this.ruleForm, 'warehouseId', this.warehouseList[0].id);
        this.wareHouseOldValId = this.warehouseList[0].id;
        this.$set(this.ruleForm, 'warehouseName', this.warehouseList[0].name);
        this.wareHouseOldValName = this.warehouseList[0].name;
      }
    },
    async loadAll() { // 根据顾客id查询已购买项目详情
      const res = await this.$api['department/consumables/customerall']();
      if (res.code === 200) {
        res.data.map(item => {
          item.value = item.name;
        });
        this.restaurants = res.data;
      }
    },
    handleClose() {
      this.visible = false;
      this.loading = false;
      this.$emit('handleClose');
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        if (restaurant.value) {
          return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        }
        return false;
      };
    },
    handleSelect(item) {
      this.customerProjectShow = true;
      this.selectCustomer = { customerId: item.id, customerSex: item.sex, customerCode: item.code, customerPhone: item.phone };
      Object.assign(this.ruleForm, this.selectCustomer);
      if (item.id) {
        this.getProjectName(item.id);
      }
      this.$set(this.ruleForm, "deptType", "代客领取");
      this.$set(this.ruleForm, "customerId", item.id);
    },
    customerClear() {
      // this.customerProjectShow = false;
      this.$set(this.ruleForm, "deptType", "科室领取");
      this.$set(this.ruleForm, "customerId", null);
    },
    async getProjectName(id) {
      const res = await this.$api['customer/customers/orderListDetails']({ customerId: id });
      if (res.code === 200) {
        this.projectNameOptions = res.data;
      }
    },
    handleConfirm() {
      if (this.selectTables.length === 0) return this.$message.error("请选择物品或者药品");
      this.loading = true;
      const deptUsrList = this.$store.getters.currentUserInfo.deptUsrList;
      const dataJson = {
        deptId: deptUsrList[0].deptId,
        deptName: deptUsrList[0].deptName,
        deptStatus: "待领取",
        receiveStatus: "待出库",
      };
      const list = [];
      Object.assign(dataJson, this.ruleForm);
      this.selectTables.forEach(item => {
        const json = {
          drugId: item.id,
          deptId: deptUsrList[0].deptId,
          deptName: deptUsrList[0].deptName,
          name: item.name,
          specl: item.spec,
          unit: item.unit,
          dataCount: item.dataCount,
          warehouseId: this.ruleForm.warehouseId,
          type: item.type,
          useFunction: item.useFunction,
          useNumber: item.useNumber,
        };
        list.push(json);
      });
      dataJson.listDto = list;
      if (this.ruleForm.id) {
        this.$api[`department/useDrugGoods/edit`]({ ...dataJson }).then(res => {
          if (res.code !== 200) return;
          this.$emit('success');
          this.msgSuccess('修改申请领取成功');
          this.handleClose();
        }).finally(() => (this.loading = false));
      } else {
        this.$api[`department/useDrugGoods/insert`]({ ...dataJson }).then(res => {
          if (res.code !== 200) return;
          this.$emit('success');
          this.msgSuccess('申请领取成功');
          this.handleClose();
        }).finally(() => (this.loading = false));
      }
    },
    async getClassificationId(val) {
      // 查询提交的产品分类id
      let api = "data/drugs/drugsList";
      if (val.dataType === "药品类") {
        api = "data/drugs/drugsList";
      } else if (val.dataType === "物品类") {
        api = "data/drugs/drugsList";
      }
      this.searchParams.productClassificationId = val.list.join(",");
      this.searchParams.warehouseId = this.ruleForm.warehouseId;
      const res = await this.$api[api]({ query: this.searchParams });
      if (res.code !== 200) return this.$message.error('查询项目列表失败！');
      this.tableDataList = res.data;
      this.tableData = JSON.parse(JSON.stringify(this.tableDataList));
      this.tableData.forEach(item => {
        this.$set(item, 'contentCount', 1);
      });
      if (this.selectTables.length > 0) {
        this.$nextTick(function() {
          this.tableData.forEach(item => {
            this.selectTables.forEach(json => {
              if (item.id === json.id) {
                this.$refs.multipleTable.toggleRowSelection(item, true);
              }
            });
          });
        });
      }
    },
    valChange(val) {
      if (val) {
        if (!this.tableDataList || this.tableDataList.length === 0) return;
        this.tableData = [];
        this.tableDataList.forEach(item => {
          if (item.name.indexOf(val) > -1 || (item.searchCode && item.searchCode.indexOf(val) > -1)) this.tableData.push(item);
        });
      } else {
        this.tableData = JSON.parse(JSON.stringify(this.tableDataList));
      }
    },
    handlechange(selection, row) {
      let isExistence = false;
      this.selectTables.forEach((item, index) => {
        if (item.id === row.id) {
          isExistence = true;
          this.selectTables.splice(index, 1);
        }
      });
      if (!isExistence) {
        const json = JSON.parse(JSON.stringify(row));
        this.$set(json, 'discount', false);
        this.$set(json, 'checkeds', true);
        // 存入当前仓库信息
        this.$set(json, 'warehouseId', this.ruleForm.warehouseId);
        this.$set(json, 'dataCount', 1);
        this.selectTables.push(json);
      }
    },
    allHandleChange(selection) {
      if (selection.length > 0) {
        selection.forEach(item => {
          let isExistence = false;
          this.selectTables.forEach(json => {
            if (json.id === item.id) {
              isExistence = true;
            }
          });
          if (!isExistence) {
            const json = JSON.parse(JSON.stringify(item));
            this.$set(json, 'discount', false);
            this.$set(json, 'checkeds', true);
            this.selectTables.push(json);
          }
        });
      } else {
        this.tableData.forEach(item => {
          this.selectTables.forEach((json, index) => {
            if (json.id === item.id) {
              this.selectTables.splice(index, 1);
              index--;
            }
          });
        });
      }
    },
    async handleDelete(items) {
      const confirmResult = await this.$confirm('请确认是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).catch((err) => err);
      if (confirmResult !== 'confirm') {
        return this.$message.info('已取消删除');
      } else {
        this.$nextTick(function() {
          this.selectTables.forEach((item, i) => {
            if (item.id === items.id) {
              this.selectTables.splice(i, 1);
            }
          });
          this.tableData.forEach(row => {
            if (items.id === row.id) {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            }
          });
          return this.$message.success('已删除成功');
        });
      }
    },
    projectChange(id) {
      console.log(id);
      this.projectNameOptions.forEach(item => {
        if (item.id === id) {
          this.ruleForm.projectName = item.projectName;
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item{
  margin-bottom: 18px;
}
</style>
